// composables/useTheme.ts
export type ThemeMode = 'light' | 'dark' | 'auto'

export interface ThemeConfig {
  mode: ThemeMode
  primaryColor: string
  colors: {
    primary: string
    success: string
    warning: string
    danger: string
    info: string
  }
}

const defaultTheme: ThemeConfig = {
  mode: 'light',
  primaryColor: '#18B3AB',
  colors: {
    primary: '#18B3AB',
    success: '#67C23A',
    warning: '#E6A23C',
    danger: '#F56C6C',
    info: '#909399'
  }
}

export const useTheme = () => {
  // 使用 localStorage 持久化主题设置
  const themeConfig = ref<ThemeConfig>(defaultTheme)
  
  // 从 localStorage 读取主题配置
  const loadThemeFromStorage = () => {
    if (import.meta.client) {
      const savedTheme = localStorage.getItem('theme-config')
      if (savedTheme) {
        try {
          themeConfig.value = { ...defaultTheme, ...JSON.parse(savedTheme) }
        } catch (e) {
          //console.warn('Failed to parse saved theme config')
        }
      }
    }
  }

  // 保存主题配置到 localStorage
  const saveThemeToStorage = () => {
    if (import.meta.client) {
      localStorage.setItem('theme-config', JSON.stringify(themeConfig.value))
    }
  }

  // 应用主题到 DOM
  const applyTheme = () => {
    if (!import.meta.client) return

    const root = document.documentElement
    const { mode, colors } = themeConfig.value

    // 设置主题模式
    if (mode === 'auto') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      root.setAttribute('data-theme', prefersDark ? 'dark' : 'light')
    } else {
      root.setAttribute('data-theme', mode)
    }

    // 设置 CSS 自定义属性
    Object.entries(colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value)
    })

    // 设置 Element Plus 主题变量
    root.style.setProperty('--el-color-primary', colors.primary)
    root.style.setProperty('--el-color-success', colors.success)
    root.style.setProperty('--el-color-warning', colors.warning)
    root.style.setProperty('--el-color-danger', colors.danger)
    root.style.setProperty('--el-color-info', colors.info)
  }

  // 切换主题模式
  const toggleTheme = () => {
    const modes: ThemeMode[] = ['light', 'dark', 'auto']
    const currentIndex = modes.indexOf(themeConfig.value.mode)
    const nextIndex = (currentIndex + 1) % modes.length
    const nextMode = modes[nextIndex]
    if (nextMode) {
      setThemeMode(nextMode)
    }
  }

  // 设置主题模式
  const setThemeMode = (mode: ThemeMode) => {
    themeConfig.value.mode = mode
    applyTheme()
    saveThemeToStorage()
  }

  // 设置主色调
  const setPrimaryColor = (color: string) => {
    themeConfig.value.primaryColor = color
    themeConfig.value.colors.primary = color
    applyTheme()
    saveThemeToStorage()
  }

  // 设置颜色
  const setColor = (key: keyof ThemeConfig['colors'], color: string) => {
    themeConfig.value.colors[key] = color
    applyTheme()
    saveThemeToStorage()
  }

  // 重置主题
  const resetTheme = () => {
    themeConfig.value = { ...defaultTheme }
    applyTheme()
    saveThemeToStorage()
  }

  // 获取当前实际主题模式（处理 auto 模式）
  const getCurrentTheme = computed(() => {
    if (themeConfig.value.mode === 'auto' && import.meta.client) {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
    }
    return themeConfig.value.mode
  })

  // 监听系统主题变化
  const watchSystemTheme = () => {
    if (!import.meta.client) return

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleChange = () => {
      if (themeConfig.value.mode === 'auto') {
        applyTheme()
      }
    }

    mediaQuery.addEventListener('change', handleChange)
    
    // 返回清理函数
    return () => mediaQuery.removeEventListener('change', handleChange)
  }

  // 初始化主题
  const initTheme = () => {
    loadThemeFromStorage()
    applyTheme()
    watchSystemTheme()
  }

  return {
    themeConfig: readonly(themeConfig),
    currentTheme: getCurrentTheme,
    toggleTheme,
    setThemeMode,
    setPrimaryColor,
    setColor,
    resetTheme,
    initTheme
  }
}
